class Snake {
    constructor() {
        this.body = [
            { x: 10, y: 10 },
            { x: 9, y: 10 },
            { x: 8, y: 10 }
        ];
        this.direction = 'right';
        this.nextDirection = 'right';
    }

    move() {
        this.direction = this.nextDirection;
        const head = { ...this.body[0] };

        switch (this.direction) {
            case 'up': head.y--; break;
            case 'down': head.y++; break;
            case 'left': head.x--; break;
            case 'right': head.x++; break;
        }

        this.body.unshift(head);
        return this.body.pop();
    }

    grow() {
        const tail = this.body[this.body.length - 1];
        this.body.push({ ...tail });
    }

    checkCollision(width, height) {
        const head = this.body[0];
        if (head.x < 0 || head.x >= width || head.y < 0 || head.y >= height) {
            return true;
        }
        return this.body.slice(1).some(segment => 
            segment.x === head.x && segment.y === head.y
        );
    }
}

class Renderer {
    constructor(ctx, gridSize) {
        this.ctx = ctx;
        this.gridSize = gridSize;
    }

    drawSnake(snake) {
        snake.body.forEach((segment, index) => {
            if (index === 0) {
                this.drawSnakeHead(segment, snake.direction);
            } else {
                this.drawSnakeBody(segment);
            }
        });
    }

    drawSnakeHead(head, direction) {
        // 绘制蛇头主体
        this.ctx.fillStyle = '#008000';
        this.ctx.fillRect(
            head.x * this.gridSize,
            head.y * this.gridSize,
            this.gridSize - 2,
            this.gridSize - 2
        );

        // 绘制蛇眼睛
        this.ctx.fillStyle = '#fff';
        const eyeSize = this.gridSize / 6;
        const eyeOffset = this.gridSize / 4;

        let leftEyeX, leftEyeY, rightEyeX, rightEyeY;

        switch (direction) {
            case 'right':
                leftEyeX = (head.x + 0.7) * this.gridSize;
                leftEyeY = (head.y + 0.3) * this.gridSize;
                rightEyeX = (head.x + 0.7) * this.gridSize;
                rightEyeY = (head.y + 0.7) * this.gridSize;
                break;
            case 'left':
                leftEyeX = (head.x + 0.3) * this.gridSize;
                leftEyeY = (head.y + 0.3) * this.gridSize;
                rightEyeX = (head.x + 0.3) * this.gridSize;
                rightEyeY = (head.y + 0.7) * this.gridSize;
                break;
            case 'up':
                leftEyeX = (head.x + 0.3) * this.gridSize;
                leftEyeY = (head.y + 0.3) * this.gridSize;
                rightEyeX = (head.x + 0.7) * this.gridSize;
                rightEyeY = (head.y + 0.3) * this.gridSize;
                break;
            case 'down':
                leftEyeX = (head.x + 0.3) * this.gridSize;
                leftEyeY = (head.y + 0.7) * this.gridSize;
                rightEyeX = (head.x + 0.7) * this.gridSize;
                rightEyeY = (head.y + 0.7) * this.gridSize;
                break;
        }

        this.ctx.beginPath();
        this.ctx.arc(leftEyeX, leftEyeY, eyeSize, 0, Math.PI * 2);
        this.ctx.arc(rightEyeX, rightEyeY, eyeSize, 0, Math.PI * 2);
        this.ctx.fill();
    }

    drawSnakeBody(segment) {
        this.ctx.fillStyle = '#00ff00';
        this.ctx.fillRect(
            segment.x * this.gridSize,
            segment.y * this.gridSize,
            this.gridSize - 2,
            this.gridSize - 2
        );
    }

    drawFood(food) {
        // 绘制食物主体
        this.ctx.fillStyle = '#ff0000';
        this.ctx.beginPath();
        this.ctx.arc(
            (food.x + 0.5) * this.gridSize,
            (food.y + 0.5) * this.gridSize,
            this.gridSize / 2 - 2,
            0,
            Math.PI * 2
        );
        this.ctx.fill();

        // 绘制高光效果
        this.ctx.fillStyle = '#fff';
        this.ctx.beginPath();
        this.ctx.arc(
            (food.x + 0.3) * this.gridSize,
            (food.y + 0.3) * this.gridSize,
            this.gridSize / 6,
            0,
            Math.PI * 2
        );
        this.ctx.fill();
    }

    clear(width, height) {
        this.ctx.clearRect(0, 0, width * this.gridSize, height * this.gridSize);
    }
}

class Game {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.gridSize = 20;
        this.width = this.canvas.width / this.gridSize;
        this.height = this.canvas.height / this.gridSize;
        
        this.snake = new Snake();
        this.renderer = new Renderer(this.ctx, this.gridSize);
        this.food = this.generateFood();
        this.score = 0;
        this.highScore = parseInt(localStorage.getItem('snakeHighScore')) || 0;
        this.speed = 5;
        this.isRunning = false;
        this.gameLoop = null;

        this.bindControls();
        this.updateHighScore();
    }

    generateFood() {
        let food;
        do {
            food = {
                x: Math.floor(Math.random() * this.width),
                y: Math.floor(Math.random() * this.height)
            };
        } while (this.snake.body.some(segment => 
            segment.x === food.x && segment.y === food.y
        ));
        return food;
    }

    bindControls() {
        document.addEventListener('keydown', (e) => {
            switch (e.key) {
                case 'ArrowUp':
                    if (this.snake.direction !== 'down') {
                        this.snake.nextDirection = 'up';
                    }
                    break;
                case 'ArrowDown':
                    if (this.snake.direction !== 'up') {
                        this.snake.nextDirection = 'down';
                    }
                    break;
                case 'ArrowLeft':
                    if (this.snake.direction !== 'right') {
                        this.snake.nextDirection = 'left';
                    }
                    break;
                case 'ArrowRight':
                    if (this.snake.direction !== 'left') {
                        this.snake.nextDirection = 'right';
                    }
                    break;
            }
        });

        document.getElementById('speed').addEventListener('input', (e) => {
            this.speed = parseInt(e.target.value);
            document.getElementById('speedValue').textContent = this.speed;
            if (this.isRunning) {
                this.stop();
                this.start();
            }
        });

        document.getElementById('startBtn').addEventListener('click', () => {
            if (this.isRunning) {
                this.stop();
                document.getElementById('startBtn').textContent = '开始游戏';
            } else {
                this.start();
                document.getElementById('startBtn').textContent = '暂停游戏';
            }
        });

        document.getElementById('restartBtn').addEventListener('click', () => {
            this.stop();
            this.reset();
        });
    }

    updateHighScore() {
        if (this.score > this.highScore) {
            this.highScore = this.score;
            localStorage.setItem('snakeHighScore', this.highScore);
        }
        document.getElementById('highScore').textContent = `最高分：${this.highScore}`;
    }

    draw() {
        this.renderer.clear(this.width, this.height);
        this.renderer.drawFood(this.food);
        this.renderer.drawSnake(this.snake);
    }

    update() {
        const oldTail = this.snake.move();

        // 检查是否吃到食物
        if (this.snake.body[0].x === this.food.x && this.snake.body[0].y === this.food.y) {
            this.snake.grow();
            this.food = this.generateFood();
            this.score += 10;
            document.getElementById('score').textContent = `分数：${this.score}`;
            this.updateHighScore();
        }

        // 检查碰撞
        if (this.snake.checkCollision(this.width, this.height)) {
            this.stop();
            alert(`游戏结束！最终得分：${this.score}`);
            this.reset();
            return;
        }

        this.draw();
    }

    start() {
        if (!this.isRunning) {
            this.isRunning = true;
            this.gameLoop = setInterval(() => this.update(), 1000 / (this.speed + 5));
        }
    }

    stop() {
        if (this.isRunning) {
            this.isRunning = false;
            clearInterval(this.gameLoop);
            this.gameLoop = null;
        }
    }

    reset() {
        this.snake = new Snake();
        this.food = this.generateFood();
        this.score = 0;
        document.getElementById('score').textContent = '分数：0';
        document.getElementById('startBtn').textContent = '开始游戏';
        this.draw();
    }
}

// 初始化游戏
const game = new Game();
game.draw();